﻿using System;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Order.Domain.ValueObject;

namespace Order.EntityFrameworkCore
{
    /// <summary>
    /// EF Core 上下文
    /// </summary>
    public class OrderContext : DbContext, IOrderContext
    {
        public OrderContext(DbContextOptions<OrderContext> options)
        : base(options)
        {
            //Database.EnsureCreated();
        }

        override protected void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
        }

        /// <summary>
        /// 订单
        /// </summary>
        public DbSet<Domain.Entity.Order> OrderInfo { get; set; }

        /// <summary>
        /// 订单明细
        /// </summary>
        public DbSet<Domain.Entity.OrderItem> OrderItemInfo { get; set; } 
        

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            var orderModelBuilder = modelBuilder.Entity<Domain.Entity.Order>();
            orderModelBuilder.ToTable("t_order").HasKey(e => e.Id);
            orderModelBuilder.HasMany(e => e.OrderItemList).WithOne().HasForeignKey(e => e.OrderId);
            orderModelBuilder.HasQueryFilter(e => e.Status);

            modelBuilder.Entity<Domain.Entity.OrderItem>().ToTable("t_order_items").HasKey(e => e.Id);
            modelBuilder.Entity<Domain.Entity.OrderItem>().OwnsOne(e => e.OrderProduct);
            modelBuilder.Entity<Domain.Entity.OrderItem>().HasQueryFilter(e => e.Status);
            base.OnModelCreating(modelBuilder);
        }
    }
}
